'use strict';
import Agenda from "agenda";
import colors from "colors";
import * as R from "ramda";
import type { Job } from "agenda";
import { mongoose } from "src/database";
import { CozeClient, config } from "src/sdk/coze";
import { mongoDB_URL } from "src/database/mongoDB";
import { modelEssayService } from "@modules/model-essay";
import { getGlobalSetting, setGlobalSetting } from "src/global-store";

const { client } = new CozeClient(config)
// 创建
export function startAgendaTask(delay?:number){  
  setTimeout(async ()=>{
    // 先判断是否存在agenda 的集合，如果存在，则需要删除才能进行后续操作，不然会失效！！！！！
    const collections =await mongoose.connection.db?.listCollections().toArray()
    if(collections?.some((value)=>value.name=='agenda')){
       await mongoose.connection.dropCollection('agenda')
    }
    const agendaInstance = new Agenda({db:{address:`${mongoDB_URL}`,collection:'agenda'}})
    agendaInstance.define('searchTask',async (job,done)=>{
        try{
          console.log('searchTask',getGlobalSetting())
          /// console.log(getGlobalSetting().xiaohongshuCookieStr,'ssss')
          // //console.log(colors.blue("searchTask workflow baseURL:"), colors.green(process.env?.APP_API_BASE_URL??'' as string))
          // const modelEssays = await modelEssayService.find({processingStatus:1},null,{updatedAt:'asc'})
          // if(modelEssays.items.length>0){
          //   const item = modelEssays.items[0];
          //   const parameters  = {
          //     composition:R.pick(['title','content'],item),
          //     uuid:item.uuid,
          //     apiBaseURL:process.env.APP_API_BASE_URL,
          //     is_test:0,
          //   }
          //   client.workflows.runs.create({
          //     workflow_id:'7527255614256267316',
          //     parameters:parameters,
          //     is_async:true
          //   }).then(async (res:any)=>{
          //     if(res.code==0){
          //       await modelEssayService.updateOne({uuid:parameters.uuid},{processingStatus:2, debugURL:res.debug_url})
          //       console.log(res)
          //     }
          //   }).catch(err=>{
          //     console.log(err);            
          //   })
          // }
          done()
        }catch(err){
          console.log(err);
        }
      })
      agendaInstance.define('searchTaskCheck',async (job,done)=>{
        try{
          console.log('searchTaskCheck')
          done()
        }catch(err){
          console.log(err);
        }
      })
    agendaInstance.on('ready',async ()=>{
      await agendaInstance.every('3 seconds','searchTask')
      await agendaInstance.every('1 seconds','searchTaskCheck')
      await agendaInstance.start();
      console.log('agenda start', mongoDB_URL)
    })
    agendaInstance.on('error', (err) => console.error('Agenda 错误:', err));
    agendaInstance.on('fail', (job, err) => console.error(`任务 ${job.name} 执行失败:`, err));
  },delay??1000)
}
